package com.lcc.lynx.security.advice;

import com.lcc.lynx.common.ResultVO;
import com.lcc.lynx.common.exception.BusinessException;
import com.lcc.lynx.common.exception.ParamsException;
import com.lcc.lynx.common.exception.e.ExcelExportException;
import com.lcc.lynx.common.exception.e.UnauthorizedException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.UUID;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 参数异常
     * @param request
     * @param response
     * @param e
     * @return
     */
    @ExceptionHandler(ParamsException.class)
    public ResultVO paramsExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        log.error("[ParamsExceptionHandler] 参数异常",e);
        return ResultVO.fail(e.getMessage());
    }

    /**
     * 未授权
     * @param request
     * @param response
     * @param e
     * @return
     */
    @ExceptionHandler(UnauthorizedException.class)
    public ResultVO unauthorizedHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        log.error("[UnauthorizedHandler] 未授权",e);
        return ResultVO.ret(401, e.getMessage());
    }


    /**
     * 业务异常
     * @param request
     * @param response
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public ResultVO businessExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        log.error("[businessExceptionHandler] 业务异常",e);
        return ResultVO.error(e.getMessage());
    }

    /**
     * Excel异常处理
     * @param request
     * @param response
     * @param e
     * @return
     */
    @ExceptionHandler(ExcelExportException.class)
    public ResultVO excelExportExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        log.error("[excelExportExceptionHandler] Excel异常",e);
        return ResultVO.error(e.getMessage());
    }

    /**
     * 全局异常处理
     * @param request
     * @param response
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Object exceptionHandler(HttpServletRequest request,HttpServletResponse response,Exception e) {
        UUID uuid = UUID.randomUUID();
        log.error("[exceptionHandler] 系统异常，错误ID："+uuid,e);
        return ResultVO.error("系统异常！请联系管理员。错误ID："+ uuid);
    }
}
